#! /bin/bash
### BEGIN INIT INFO
# Provides:          lance_tool 
# Required-Start:    $network $local_fs
# Required-Stop:     $network $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      1
# Short-Description: Start lance_tool
# Description: Start and Stop the lance_tool
### END INIT INFO
# chkconfig: 345 20 80
# description: Lance Tool
# /etc/init.d/lance_*

setup_nat=""

function this_proc_pid(){
  ps -elf | grep `basename $0` | grep background | grep -v grep | awk '{print $4}' | head -n 1
}

case "$1" in
    start)
        nohup $0 background >/dev/null 2>&1 &
        sleep 3
        PID=`this_proc_pid`
        echo "started `basename $0` [$PID]"
        exit 0
    ;;

    stop)
        PID=`this_proc_pid`
        if [ "$PID" != "" ]
        then
            kill -s 9 $PID
            sleep 3
            echo "stopped `basename $0` [$PID]"
        else
            echo "nothing to do."
        fi
        exit 0
    ;;

    restart)
        $0 stop
        $0 start
        exit 0
    ;;

    status)
        PID=`this_proc_pid`
        if [ "$PID" != "" ]
        then
          echo "`basename $0` was running ...... [$PID]"
        else
          echo "`basename $0` was not running"
        fi
        exit 0
    ;;

    background)
        while [ 1 ]
        do
          route | grep "10.0.0.0" | grep "ppp"
          if [ $? -ne 0 ]
          then
            $setup_nat fixppp
          fi
          sleep 10
        done
        exit 0
    ;;

    install)
        CUR_DIR="`pwd`"
        cd "`dirname $0`"
        SCR_PATH="`pwd`"
        setup_nat="$SCR_PATH"/setup_nat.sh
        cat `basename $0` | awk '{\
          if ($0 ~ /^setup_nat=.+/){\
            print "setup_nat=""'"$setup_nat"'";\
          } else {\
            print $0;\
          }\
        }' > /etc/init.d/`basename $0`
        chmod +x /etc/init.d/`basename $0`
        chkconfig `basename $0` on 2>/dev/null
        chkconfig `basename $0` on 2>/dev/null
        cd "$CUR_DIR"
        exit 0
    ;;

    *)
        echo "Usage: /etc/init.d/`basename $0` {start|stop|restart|status}"
        exit 1
    ;;
esac


